<?php
namespace Components\Account\User;

class WalletLogLogic {
  private function getPaginate($builder, $limit, $page) {
    return ['code' => 0, 'models'=>(new \Phalcon\Paginator\Adapter\QueryBuilder([
      'builder' => $builder,
      'limit' => $limit,
      'page' => $page
    ])) -> getPaginate()];
  }

  public function createBuilder($parameters, $logModel) {
    $builder = Adapter::getDI('modelsManager') -> createBuilder()
      -> from([
        'log'  => $logModel,
        'account'  => __NAMESPACE__ . '\\Model',
        'from_account'  => __NAMESPACE__ . '\\Model'
      ])
      -> where('log.user_id = account.user_id AND log.from_user_id = from_account.user_id')
      -> columns(
        'log.*,'.
        'account.user_code as account_user_code,'.
        'from_account.user_code as from_account_user_code'
      )
      -> orderBy('log.id DESC');

    if(isset($parameters['conditions'])) {
      foreach($parameters['conditions'] as $m => $conditions) {
        foreach($conditions as $k => $v) {
          if(!empty($v)) {
            $builder -> andWhere($m . '.' . $k . ' = "' . $v . '"');
          }
        }
      }
    }

    return $builder;
  }

  public function pagerByField($value, $parameters, $limit = 10, $page = 1) {
    $value = intval($value);
    if($value <= 0) {
      return $this -> response -> setJsonContent(['code' => -1, 'message'=>'此类型不存在']);
    }

    $resWalletLogModel = Adapter::getWalletLogServiceInstance() -> getModelClassNameByField($value);
    if($resWalletLogModel['code'] != 0) {
      return $resWalletLogModel;
    }

    return $this -> getPaginate(
      $this -> createBuilder($parameters, $resWalletLogModel['class_name']),
      $limit,
      $page
    );
  }
}
